#$ARGV[0] is the RSSI model log file.
#$ARGV[1] is the user-defined interval that are considered.
#		e.g., log file has a 2ms time granularity, if you want 10ms, then set ARGV[1] as 10.
#		default is 2ms.
#$ARGV[2] is the number of readings that are considered.
#			All readings as default.

$file = $ARGV[0];
$totalNum = 1000000000;
$RSSIthreshold = -83;
# sampleInterval stands for the original time granularity 
#in the RSSI log file. 2 stands for 2ms,10 stands 10ms.
$sampleInterval = 2; 
$granularity = $sampleInterval;
if($ARGV[2]!=0){
	$totalNum = $ARGV[2];
}
if($ARGV[1]!=0){
	$granularity = $ARGV[1];
}

@pathname = split(/\\/,$file);
$len = @pathname;
$path;
print "$len\n";
for($i=$len-2;$i>=0;$i--){
	$path = "$pathname[$i]\\"."$path";
	print "$path\n";
}

$channelNum = 16;
@samples;
# for($i=0;$i<$totalNum;$i++){
	# for($j=0;$j<$channelNum+1;$j++) {
		# $samples[$i][$j] = 0;
	# }
# }

@totalIdle;
@totalBusy;
for($i=0;$i<$channelNum+1;$i++){
	$totalBusy[$i] = 0;
	$totalIdle[$i] = 0;
}


#get the samples from log file
$alreadyNum = 0;
# if interval is 2ms, desired granularity is 10ms, then counter is 5.
$granCounter = $granularity/$sampleInterval; 
$smallcounter = 0;
open fin, "<$file" or die "can not open file $file!\n";
GETSAMPLE:{
for($i=0;$i<$channelNum+1;$i++){
				$samples[$alreadyNum][$i]=0;
}
	while (<fin>) {
		chomp;
		@info = split;

		$length = @info;
		if(($length-1)!=$channelNum){
			last GETSAMPLE;
		}
		
		for($i=0;$i<$channelNum+1;$i++){
			if($i==0){
				if($smallcounter%$granCounter ==0){
					$samples[$alreadyNum][$i]=$info[$i];
				}
				else {
					#do nothing
				}
			}
			else{
				if($info[$i]>=$RSSIthreshold){
					$samples[$alreadyNum][$i]=1;
				}
			}
		}
		
		$smallcounter++;
		if($smallcounter%$granCounter==0){
			for($i=0;$i<$channelNum+1;$i++){
				if($samples[$alreadyNum][$i]==0){
					$totalIdle[$i]++;
				}
			}
			$alreadyNum++;
			for($i=0;$i<$channelNum+1;$i++){
				$samples[$alreadyNum][$i]=0;
			}
		}
		if($alreadyNum==$totalNum){
			last GETSAMPLE;
		}
	}
}
close fin;

$totalNum=$alreadyNum;
print "totalNum: $totalNum\n";
open OR, ">$path\\occupRatioSync.dat" or die "can not open file .\\occupRatioSync.dat\n";
for($i=1;$i<$channelNum+1;$i++){
	#$occupRatio = $totalBusy[$i]/$totalNum;
	$idleRatio = $totalIdle[$i]/$totalNum;
	$occupRatio = 1-$idleRatio;
	$totalBusy[$i]=$totalNum-$totalIdle[$i];
	print "totalBusy$i: $totalBusy[$i] $totalIdle[$i]\n";
	print OR "$totalBusy[$i] $totalIdle[$i] $occupRatio $idleRatio\n";
}
close OR;
print "$samples[2][100]\n";
#output 01 log file.
open fout, ">$path\\totalSync01Granu$granularity.info" or die "can not open file .\\totalSync01Granu$granularity.info\n";
for($i=0;$i<$totalNum;$i++){
	for($j=0;$j<$channelNum+1;$j++) {
		print fout "$samples[$i][$j] ";
		
	}
	print fout "\n";
}
close fout;


